import React, { useState } from 'react';
import { Input, Button, Toast } from 'antd-mobile';
import axios from '../axiosInstance';

function LoginPage({ onLogin }) {
  const [mode, setMode] = useState('login'); // 'login' or 'register' or 'reset'
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [loading, setLoading] = useState(false);
  const [resetPwd, setResetPwd] = useState('');
  const [resetConfirm, setResetConfirm] = useState('');

  // 校验密码是否为六位数字
  const isValidPassword = (pwd) => /^\d{6}$/.test(pwd);

  // 事件处理函数
  const handleUsernameChange = (val) => setUsername(val);
  const handlePasswordChange = (val) => setPassword(val);
  const handleConfirmChange = (val) => setConfirm(val);
  const handleResetPwdChange = (val) => setResetPwd(val);
  const handleResetConfirmChange = (val) => setResetConfirm(val);

  const switchToRegister = () => {
    setMode('register');
    setPassword('');
    setConfirm('');
  };
  const switchToLogin = () => {
    setMode('login');
    setPassword('');
    setConfirm('');
    setResetPwd('');
    setResetConfirm('');
  };
  const switchToReset = () => {
    setMode('reset');
    setResetPwd('');
    setResetConfirm('');
    setPassword('');
    setConfirm('');
  };

  // 登录、注册、重置密码提交
  const handleSubmit = async () => {
    if (!username.trim()) {
      Toast.show({ content: '请输入用户名' });
      return;
    }
    if (mode === 'login' || mode === 'register') {
      if (!isValidPassword(password)) {
        Toast.show({ content: '密码必须为6位数字' });
        return;
      }
    }
    if (mode === 'register') {
      if (password !== confirm) {
        Toast.show({ content: '两次密码输入不一致' });
        return;
      }
    }
    if (mode === 'reset') {
      if (!isValidPassword(resetPwd)) {
        Toast.show({ content: '新密码必须为6位数字' });
        return;
      }
      if (resetPwd !== resetConfirm) {
        Toast.show({ content: '两次新密码输入不一致' });
        return;
      }
    }
    setLoading(true);
    try {
      if (mode === 'register') {
        await axios.post('/user/register', {
          username,
          password,
          confirm
        });
        Toast.show({ content: '注册成功，请登录' });
        setMode('login');
        setPassword('');
        setConfirm('');
      } else if (mode === 'login') {
        const res = await axios.post('/user/login', {
          username,
          password
        });
        Toast.show({ content: '登录成功' });
        localStorage.setItem('token', res.data.token);
        localStorage.setItem('username', username);
        if (onLogin) onLogin(username);
      } else if (mode === 'reset') {
        await axios.post('/user/reset_password', {
          username,
          new_password: resetPwd,
          confirm: resetConfirm
        });
        Toast.show({ content: '密码重置成功，请登录' });
        setMode('login');
        setResetPwd('');
        setResetConfirm('');
        setPassword('');
        setConfirm('');
      }
    } catch (e) {
      Toast.show({ content: e?.response?.data?.detail || '请求失败' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 320, margin: '60px auto', padding: 24, background: '#fff', borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
      <h2 style={{ textAlign: 'center', marginBottom: 24 }}>
        {mode === 'login' && '登录'}
        {mode === 'register' && '注册'}
        {mode === 'reset' && '重置密码'}
      </h2>
      <Input
        placeholder="用户名"
        value={username}
        onChange={handleUsernameChange}
        clearable
        style={{ marginBottom: 16 }}
      />
      {(mode === 'login' || mode === 'register') && (
        <Input
          placeholder="密码（6位数字）"
          value={password}
          onChange={handlePasswordChange}
          type="password"
          clearable
          maxLength={6}
          style={{ marginBottom: 16 }}
        />
      )}
      {mode === 'register' && (
        <Input
          placeholder="确认密码"
          value={confirm}
          onChange={handleConfirmChange}
          type="password"
          clearable
          maxLength={6}
          style={{ marginBottom: 16 }}
        />
      )}
      {mode === 'reset' && (
        <>
          <Input
            placeholder="新密码（6位数字）"
            value={resetPwd}
            onChange={handleResetPwdChange}
            type="password"
            clearable
            maxLength={6}
            style={{ marginBottom: 16 }}
          />
          <Input
            placeholder="确认新密码"
            value={resetConfirm}
            onChange={handleResetConfirmChange}
            type="password"
            clearable
            maxLength={6}
            style={{ marginBottom: 16 }}
          />
        </>
      )}
      <Button block color="primary" loading={loading} onClick={handleSubmit}>
        {mode === 'login' && '登录'}
        {mode === 'register' && '注册'}
        {mode === 'reset' && '重置密码'}
      </Button>
      <div style={{ textAlign: 'right', marginTop: 12 }}>
        {mode === 'login' && (
          <>
            <span style={{ color: '#1677ff', cursor: 'pointer', marginRight: 12 }} onClick={switchToRegister}>没有账号？注册</span>
            <span style={{ color: '#1677ff', cursor: 'pointer' }} onClick={switchToReset}>忘记密码？</span>
          </>
        )}
        {mode === 'register' && (
          <span style={{ color: '#1677ff', cursor: 'pointer' }} onClick={switchToLogin}>已有账号？登录</span>
        )}
        {mode === 'reset' && (
          <span style={{ color: '#1677ff', cursor: 'pointer' }} onClick={switchToLogin}>返回登录</span>
        )}
      </div>
    </div>
  );
}

export default LoginPage;